<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import {
  getDashboardStats,
  getTopCities,
  getActivityTrend,
  getUserGrowth,
  getContentCategory
} from '@/api/dashboard'

// 统计数据
const stats = ref([
  {
    title: '用户总数',
    value: '0',
    icon: 'User',
    color: '#409eff',
    trend: '+0%'
  },
  {
    title: '游记总数',
    value: '0',
    icon: 'Document',
    color: '#67c23a',
    trend: '+0%'
  },
  {
    title: '旅行计划',
    value: '0',
    icon: 'Calendar',
    color: '#e6a23c',
    trend: '+0%'
  },
  {
    title: '城市数量',
    value: '0',
    icon: 'Location',
    color: '#f56c6c',
    trend: '+0%'
  }
])

// 加载统计数据
const loadStats = async () => {
  try {
    const result = await getDashboardStats()
    if (result.success) {
      const data = result.data
      stats.value[0].value = data.totalUsers.toLocaleString()
      stats.value[0].trend = data.userGrowthRate
      stats.value[1].value = data.totalNotes.toLocaleString()
      stats.value[1].trend = data.noteGrowthRate
      stats.value[2].value = data.totalPlans.toLocaleString()
      stats.value[3].value = data.totalCities.toLocaleString()
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 图表实例
let userTrendChart = null
let categoryChart = null
let regionChart = null
let activityChart = null

// 初始化用户增长趋势图
const initUserTrendChart = async () => {
  const chartDom = document.getElementById('user-trend-chart')
  if (!chartDom) {
    console.error('找不到 user-trend-chart 元素')
    return
  }

  userTrendChart = echarts.init(chartDom)

  try {
    const result = await getUserGrowth()
    if (result.success) {
      const { days, newUserData, activeUserData } = result.data

      const option = {
        title: {
          text: '用户增长趋势（最近7天）',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['新增用户', '活跃用户'],
          top: '10%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: days,
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增用户',
            type: 'bar',
            data: newUserData,
            itemStyle: {
              color: '#409eff'
            }
          },
          {
            name: '活跃用户',
            type: 'line',
            data: activeUserData,
            smooth: true,
            itemStyle: {
              color: '#67c23a'
            }
          }
        ]
      }

      userTrendChart.setOption(option)
    }
  } catch (error) {
    console.error('加载用户增长趋势失败:', error)
  }
}

// 初始化内容分类饼图
const initCategoryChart = async () => {
  const chartDom = document.getElementById('category-chart')
  if (!chartDom) {
    console.error('找不到 category-chart 元素')
    return
  }

  categoryChart = echarts.init(chartDom)

  try {
    const result = await getContentCategory()
    if (result.success) {
      const categoryData = result.data.map((item, index) => {
        const colors = ['#409eff', '#67c23a', '#e6a23c']
        return {
          value: item.value,
          name: item.name,
          itemStyle: { color: colors[index] || '#909399' }
        }
      })

      const option = {
        title: {
          text: '内容分类统计',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: '15%'
        },
        series: [
          {
            name: '内容类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '60%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: categoryData
          }
        ]
      }

      categoryChart.setOption(option)
    }
  } catch (error) {
    console.error('加载内容分类统计失败:', error)
  }
}

// 初始化热门城市柱状图（按推荐数排序）
const initRegionChart = async () => {
  const chartDom = document.getElementById('region-chart')
  if (!chartDom) return

  regionChart = echarts.init(chartDom)

  try {
    const result = await getTopCities()
    if (result.success) {
      const cities = result.data
      const cityNames = cities.map((city) => city.name).reverse()
      const cityValues = cities.map((city) => city.value).reverse()

      const option = {
        title: {
          text: '热门城市 TOP 10（按推荐数）',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: cityNames
        },
        series: [
          {
            name: '推荐数',
            type: 'bar',
            data: cityValues,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#409eff' },
                { offset: 1, color: '#67c23a' }
              ])
            }
          }
        ]
      }

      regionChart.setOption(option)
    }
  } catch (error) {
    console.error('加载热门城市排行失败:', error)
  }
}

// 初始化平台活跃度折线图
const initActivityChart = async () => {
  const chartDom = document.getElementById('activity-chart')
  if (!chartDom) return

  activityChart = echarts.init(chartDom)

  try {
    const result = await getActivityTrend()
    if (result.success) {
      const { months, viewData, postData } = result.data

      const option = {
        title: {
          text: '平台活跃度趋势（最近12个月）',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['浏览量', '发帖量'],
          top: '10%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: months
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '浏览量',
            type: 'line',
            smooth: true,
            data: viewData,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.8)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            },
            itemStyle: {
              color: '#409eff'
            }
          },
          {
            name: '发帖量',
            type: 'line',
            smooth: true,
            data: postData,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(103, 194, 58, 0.8)' },
                { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
              ])
            },
            itemStyle: {
              color: '#67c23a'
            }
          }
        ]
      }

      activityChart.setOption(option)
    }
  } catch (error) {
    console.error('加载平台活跃度趋势失败:', error)
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  userTrendChart?.resize()
  categoryChart?.resize()
  regionChart?.resize()
  activityChart?.resize()
}

onMounted(() => {
  // 加载统计数据
  loadStats()

  // 使用 nextTick 确保 DOM 完全渲染
  nextTick(() => {
    setTimeout(() => {
      initRegionChart()
      initActivityChart()
      initUserTrendChart()
      initCategoryChart()
    }, 300)
  })

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  console.log('Dashboard 组件即将卸载')
  // 销毁图表实例
  userTrendChart?.dispose()
  categoryChart?.dispose()
  regionChart?.dispose()
  activityChart?.dispose()

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="dashboard">
    <h2 class="page-title">📊 仪表盘</h2>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in stats" :key="stat.title">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ background: stat.color }">
              <el-icon :size="32"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
              <div class="stat-trend">{{ stat.trend }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="content-row">
      <!-- 热门地区 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <div id="region-chart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 平台活跃度 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <div id="activity-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="content-row">
      <!-- 用户增长趋势 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <div id="user-trend-chart" class="chart"></div>
        </el-card>
      </el-col>

      <!-- 内容分类统计 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <div id="category-chart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 统计卡片 */
.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.stat-card :deep(.el-card__body) {
  padding: 16px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.stat-icon :deep(.el-icon) {
  font-size: 24px;
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 22px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.2;
}

.stat-title {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-trend {
  font-size: 12px;
  color: #67c23a;
  font-weight: 600;
}

/* 图表区域 */
.content-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: visible;
}

.chart-card :deep(.el-card__body) {
  padding: 20px;
  height: 100%;
}

.chart {
  width: 100%;
  height: 420px;
  min-height: 420px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }

  .page-title {
    font-size: 20px;
  }

  .stat-value {
    font-size: 24px;
  }

  .stat-icon {
    width: 48px;
    height: 48px;
  }

  .stat-icon :deep(.el-icon) {
    font-size: 24px !important;
  }

  .chart {
    height: 300px;
  }
}

@media (max-width: 992px) {
  .content-row {
    margin-bottom: 0;
  }
}
</style>
